package com.lxl.redis;

import com.lxl.util.PropertyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @program: kettleweb2.0
 * @author: wuchun
 * @description:
 * @create: 2018/9/29 18:41
 */
public class JedisConfig {

    private static String host = PropertyUtil.getProperty("redis.server.host");
    private static int port = Integer.parseInt(PropertyUtil.getProperty("redis.server.port"));
    private static String password = PropertyUtil.getProperty("redis.server.password");
    private static int maxTotal = Integer.parseInt(PropertyUtil.getProperty("redis.server.maxTotal"));
    private static int maxIdle = Integer.parseInt(PropertyUtil.getProperty("redis.server.maxIdle"));
    private static int maxWaitMillis = Integer.parseInt(PropertyUtil.getProperty("redis.server.maxWaitMillis"));
    private static int timeOut = Integer.parseInt(PropertyUtil.getProperty("redis.server.timeOut"));

    /**
     * 初始化redis连接池
     */
    private static JedisPool jedisPool = null;

    static {
        JedisPoolConfig config = new JedisPoolConfig();
        // 设置最大连接数
        // 可以创建3000jedis实例
        config.setMaxTotal(maxTotal);
        // 设置最大空闲连接数
        config.setMaxIdle(maxIdle);
        // 等待可用连接的最大时间
        config.setMaxWaitMillis(maxWaitMillis);
        // 在borrow一个jedis实例时，是否提前进行validate操作；如果为true，则得到的jedis实例均是可用的
        config.setTestOnBorrow(true);
        jedisPool = new JedisPool(config, host, port);
    }

    /**
     * 获取Jedis实例
     * 每次用完要将连接返回给连接池 jedis.close();
     */
    public synchronized static Jedis getJedis() {
        if (jedisPool != null) {
            Jedis resource = jedisPool.getResource();
            return resource;
        } else {
            return null;
        }
    }


}
